import vue from '@vitejs/plugin-vue';
// import styleImport from 'vite-plugin-style-import';
const { resolve } = require('path');
import { defineConfig } from 'vite';
import viteCompression from 'vite-plugin-compression';
import fs from 'fs';
import dotenv from 'dotenv';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
import ElementPlus from 'unplugin-element-plus/vite';
try {
  // 根据环境变量加载环境变量文件
  const file = dotenv.parse(fs.readFileSync(`.env.${process.env.NODE_ENV}`));
  // 根据获取的key给对应的环境变量赋值
  for (const key in file) {
    process.env[key] = file[key];
  }
} catch (e) {
  console.error(e);
}
const VITE_BUILD_ENV = process.env.VITE_BUILD_ENV;

let base;
// 配置环境变量，测试与生产环境项目资源放在oss上
if (VITE_BUILD_ENV == 'dev') {
  base = '/manage/';
} else if (VITE_BUILD_ENV == 'test') {
  base = 'https://test-qcy-oss.peogoo.com/etcmanager/';
} else {
  base = '/manage/';
}

export default defineConfig({
  base: '/',
  resolve: {
    alias: [{ find: '@', replacement: resolve(__dirname, 'src') }],
  },
  server: {
    // proxy: {
    //   '/api': {
    //     target: 'xxxx',
    //     changeOrigin: true,
    //     rewrite: path => path.replace(/^\/api/, '/'),
    //   },
    // },
  },
  build: {
    assetsDir: './static',
    chunkSizeWarningLimit: 500,
    sourcemap: false,
    minify: 'terser',
    cssCodeSplit: true, // 如果设置为false，整个项目中的所有 CSS 将被提取到一个 CSS 文件中
    rollupOptions: {
      output: {
        manualChunks: {
          // 拆分代码
          vue: ['vue', 'vue-router', 'vuex'], // 如果打包有BUG请屏蔽
          'element-plus': ['element-plus'],
          // echarts: ['echarts'],
        },
      },
    },
    terserOptions: {
      compress: {
        // warnings: false,
        drop_console: true,
        drop_debugger: true,
        pure_funcs: ['console.log'],
      },
      output: {
        // 去掉注释内容
        comments: true,
      },
    },
    brotliSize: false,
  },
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@use "./src/assets/css/theme-chalk.scss" as *;`,
        javascriptEnabled: true,
      },
    },
  },
  plugins: [
    vue(),
    viteCompression(),
    ElementPlus({
      importStyle: 'sass',
      useSource: true,
    }),
    Components({
      resolvers: [
        ElementPlusResolver({
          importStyle: 'sass',
        }),
      ],
    }),
  ],
});
